package gold.digger;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC278 {
    public long startExecuteTime = System.currentTimeMillis();


    /* The isBadVersion API is defined in the parent class VersionControl.
      boolean isBadVersion(int version); */


    class VersionControl {
        boolean isBadVersion(int version) {
            return version >= 7;
        }
    }

    public class Solution extends VersionControl {
        public int firstBadVersion(int n) {
            return firstBadVersionByBinarySearch(1, n);
        }

        public int firstBadVersionByBinarySearch(int start, int end) {
            if (end < start) return end;
            while (start <= end) {
                int mid = start + (end - start) / 2;
                if (isBadVersion(mid)) {
                    if (mid - 1 >= start) {
                        if (isBadVersion(mid - 1)) {
                            end = mid - 1;
                        } else {
                            return mid;
                        }
                    } else {
                        return start;
                    }
                } else {
                    start = mid + 1;
                }
            }

            return start;
        }
    }

    public void run() {
        Solution solution = new Solution();
        System.out.println(solution.firstBadVersion(100));
    }

    public static void main(String[] args) throws Exception {
        LC278 an = new LC278();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
